package com.example.gpstracking;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.text.format.Time;
import android.util.Log;

public class WifiScanner extends Service {
	
	String location = location = (Environment.getExternalStorageDirectory()+ "/data.xml");
	
	GPSTracker tracker;
	// wifi enabled
	boolean iswifion = false;
	
	// starte demon
	boolean enabled = true;

	public void disableScanner() {
		this.enabled = false;
	}

	// results
	List<ScanResult> list;
	//
	WifiManager wifim;

	Context context;

	public WifiScanner(Context context, GPSTracker tracker) {

		this.context = context;
		// SystemService holen
		wifim = (WifiManager) context.getSystemService(WIFI_SERVICE);
//		gps = new GPSTracker(context) ;
		this.tracker = tracker;
	}

	public boolean scan() {

		iswifion = wifim.isWifiEnabled();
		System.out.println("ison");

		if (!iswifion) {
			wifim.setWifiEnabled(true);
		}
		boolean mycase = wifim.startScan();
		if (mycase) {

			System.out.println("success");

			list = wifim.getScanResults();

		}

		return mycase;

	}

	public List<ScanResult> results() {

		return list;

	}
	
	
	public void writeData(){
		
		String filename = "filename.txt";
			
			
		
//		while (iswifion && enabled){
	try {
		//GPS
//		if (gps.canGetLocation()) {
//
//			double latitude = gps.getLatitude();
//			double longitude = gps.getLongitude();
//			CharSequence myCharsequence = String.valueOf(latitude);
//			CharSequence myCharsequence2 = String.valueOf(longitude);
//	
//
//			// \n is for new line
//
//			// Toast.makeText(getApplicationContext(),
//			// "Your Location is - \nLat: " + latitude + "\nLong: " +
//			// longitude, Toast.LENGTH_LONG).show();
//		} else {
//			// can't get location
//			// GPS or Network is not enabled
//			// Ask user to enable GPS/network in settings
//			gps.showSettingsAlert();
//		}
//		
		
		scan();
//		File file = new File(Environment.getExternalStorageDirectory(), filename);
//		FileOutputStream fos = new FileOutputStream(file);
//		PrintWriter out = new PrintWriter(new BufferedOutputStream(fos));
		
		String[][] myarray = new String[list.size()][5];
		int counter =0;
		    Iterator iter = list.iterator();
			while (iter.hasNext()&& counter < list.size()){
				ScanResult result = (ScanResult) iter.next();
				myarray [counter][0]= result.BSSID;
				myarray [counter][1]= result.SSID;
				myarray [counter][2]= result.capabilities;
				myarray [counter][3]= String.valueOf(result.frequency);
				myarray [counter][4]= String.valueOf(result.level);
				
				
			
				System.out.println(myarray [counter][0]);
				counter++;
				
//				CharSequence myseq = String.valueOf(result);
//			out.append(myseq);
			}
		   
//			out.append("entry");
//
//		    
//		
//			 out.flush();
//			out.close();
			
			
			String[] koords = new String [2];
			if (tracker.canGetLocation()){
			
			double latitude = tracker.getLatitude();
			double longitude = tracker.getLongitude();
			String myCharsequence = String.valueOf(latitude);
			String myCharsequence2 = String.valueOf(longitude);
			
				koords[0]=  myCharsequence;
				koords[1] = myCharsequence2;
				System.out.println(koords[0] + "      " + koords[1]);
			}
//			String name = "asdf1234.txt";
			
			
			FileWriter write = new FileWriter(location);
			
			write.rewrite_file(location, koords, myarray);
			
//			Client_Socket conn = new Client_Socket();
//			if (conn.isenabled()){System.out.println("fuckkkk");}
		    
		} catch (Exception e) {
		   e.printStackTrace();
					   
			
			
		}

//		}
		}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	// public Scanner(Context context){
	// this.context = context;
	// }
	//
	// public boolean IsCurrentConnectedWifi(ScanResult scanResult)
	// {
	// WifiManager mainWifi = (WifiManager)
	// context.getSystemService(WIFI_SERVICE);
	// WifiInfo currentWifi = mainWifi.getConnectionInfo();
	// if(currentWifi != null)
	// {
	// if(currentWifi.getSSID() != null)
	// {
	// if(currentWifi.getSSID() == scanResult.SSID)
	// return true;
	// }
	// }
	// return false;
	// }
	//

	//
	//
	// private TimerTask scanTask;
	// private Handler handler;
	//
	// private List<ScanResult> sResults;
	// private Timer t;
	//
	// public void doWifiScan(){
	// wifiManager = (WifiManager)
	// context.getSystemService(context.CONNECTIVITY_SERVICE);
	// scanTask = new TimerTask() {
	//
	//
	// public void run() {
	// handler.post(new Runnable() {
	//
	//
	//
	//
	// public void run() {
	//
	// sResults = wifiManager.getScanResults();
	// if(sResults!=null)
	// Log.d("TIMER", "sResults count" + sResults.size());
	// listallAPs(sResults);
	//
	// }
	// });
	// }};
	//
	// t.schedule(scanTask, 3000, 30000);
	// }
	//
	// public void listallAPs(List<ScanResult> sResults){
	//
	// ScanResult bestSignal = null;
	// for (ScanResult result : sResults) {
	// if (bestSignal == null
	// || WifiManager.compareSignalLevel(bestSignal.level, result.level) < 0)
	// bestSignal = result;
	// }
	//
	// String message =
	// String.format("%s networks found. %s is the strongest. %s is the bsid",
	// sResults.size(), bestSignal.SSID, bestSignal.BSSID);
	//
	// Log.d("sResult", message);
	// System.out.println(bestSignal);
	// }

}
